<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="css/public.css" rel="stylesheet" />
    <link href="css/index.css" rel="stylesheet" />

</head>
<body>

<ul id="pro-list">


</ul>

<script>
//样式重置表

    var listData = [
        {
            pid:1,
            pname:"iphone 8",
            price:6000,
            imgUrl:""
        },
        {
            pid:2,
            pname:"华为 荣耀666",
            price:8000,
            imgUrl:""
        },
        {
            pid:3,
            pname:"小米 note 10",
            price:3000,
            imgUrl:""
        }
    ];

    var oList =document.getElementById("pro-list");

    var str = "";
    for(var i=0;i<listData.length;i++){
        str+='<li class="pro-item" >' +
                '<p>'+listData[i].pname+'</p>' +
                '<p>价格：'+listData[i].price+'</p>' +
                '<img width="100" height="100" src="'+listData[i].imgUrl+'">' +
            '</li>'
    }

    oList.innerHTML = str;


    //给每隔li加点击事件
    var aLi = document.getElementsByTagName("li");
    for(var i=0;i<aLi.length;i++){
        aLi[i].index = i;
        aLi[i].onclick=function () {

            //先获取得到之前的历史记录，再往里面添加

            var proHistory = window.localStorage.getItem("pro-history")||"[]"; //获取之前的历史记录
            console.log(typeof proHistory) //null
            proHistory = JSON.parse(proHistory); //格式转换

            //把当前浏览的内容添加到历史记录
            var current = listData[this.index];
            var hasCurrent = false;
            for(var i=0;i<proHistory.length;i++){
                if(proHistory[i].pid == current.pid){
                    //说明历史记录已经存在,让当前商品排在第一位
                    hasCurrent = true;
                    proHistory[i] = proHistory[0];
                    proHistory[0] = current;
                   // proHistory.splice(i,1)//删

                }
            }
            //等循环结束，判断历史记录是否存在
            if(!hasCurrent){
                //如果不存在就添加
                proHistory.unshift(current)
            }



            //保存历史记录   localStorage保存的值应该是字符串
            window.localStorage.setItem("pro-history",JSON.stringify(proHistory));
            console.log(window.localStorage.getItem("pro-history"));

            //然后页面跳转
            //window.location.href="demo-detail.html"
        }
    }




</script>
</body>
</html>